package com.suzhiliang.springbootlesson.login;

import com.suzhiliang.springbootlesson.springDataJPAToCRUD.UserEntity;
import com.suzhiliang.springbootlesson.springDataJPAToCRUD.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 登录的Controller
 */
@RestController
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private UserJPA userJPA;

    @RequestMapping("/login")
    public String login(UserEntity user, HttpServletRequest request) {
        String loginInfo = "登录成功";

        boolean flag = true;
        Optional<UserEntity> userEntity = userJPA.findOne(new Specification<UserEntity>() {
            @Override
            public Predicate toPredicate(Root<UserEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder
                    criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("name"), user.getName()));
                return null;
            }
        });
        if (!userEntity.isPresent()) {
            flag = false;
            loginInfo = "用戶不存在登录失败";
        }else if(!userEntity.get().getPassword().equals(user.getPassword())){
            flag = false;
            loginInfo = "密码错误登录失败";
        }
        //登录成功时将用户信息写入session
        if(flag){
            request.getSession().setAttribute("session_user",userEntity);
        }
          return loginInfo;
    }
}
